package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        System.out.println(request.getRequestURL());
        System.out.println(request.getMethod());

        //解决跨域拦截与静态请求拦截
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //handler 请求映射方法的处理器
        /**
         * 1.springmvc启动的时候会将所有的请求映射方法解析，并封装成一个对象：handlerMethod
         * 这个对象包含请求映射方法里面所有映射信息，包括方法上的注解
         * 2.springmvc定义了一个类似map对象来管理所有的handlerMethod对象
         * key为映射方法的url路径，value为映射方法对象
         * 3.浏览器发起请求时，服务器解析url，获得handlerMethod对象
         * 4.springmvc会立即调用
         */

        //1.识别请求方法头顶上是否有这个注解CheckLoginInterceptor的preHandle方法，传入参数handlerMethod
        //获取token
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        HandlerMethod hm=(HandlerMethod)handler;
        if(hm.hasMethodAnnotation(RequireLogin.class)){
            if(userInfo==null){
                  response.setContentType("application/json;charset=utf-8");
                   response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                  return false;
             }
        }
        return true;
    }
}
